//
//  IconTextView.m
//  NeteaseLottery
//
//  Created by  on 11-11-9.
//  Copyright (c) 2011年 netease. All rights reserved.
//

#import "ZBIconTextView.h"


@implementation ZBIconTextView

@synthesize iconView=_iconView;
@synthesize textLabel=_textLabel;
@synthesize centerAlignment=_centerAlignment;
@synthesize verticalPadding=_verticalPadding;
@synthesize textFirst=_textFirst;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _iconView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:_iconView];
        _textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _textLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:_textLabel];
        
        _verticalPadding = 5;
    }
    return self;
}

-(void)dealloc {
    [_iconView release];
    [_textLabel release];
    [super dealloc];
}

-(void)setImage:(UIImage*)image {
    _iconView.image = image;
    [self setNeedsLayout];
}

-(void)setText:(NSString*)text {
    _textLabel.text = text;
    [self setNeedsLayout];
}

-(void)resizeToContent {
    UIImage *image = _iconView.image;
    CGSize iconSize = image.size;    
    CGSize textSize = [_textLabel.text sizeWithFont:_textLabel.font forWidth:320 lineBreakMode:UILineBreakModeWordWrap];
    CGRect frame = self.frame;
    frame.size.width = 6+iconSize.width+textSize.width;
    frame.size.height = 4 + MAX(iconSize.height, textSize.height);
}

-(void)layoutSubviews {
    CGFloat space = 2.0;
    
    UIImage *image = _iconView.image;
    CGSize iconSize = image.size;
    
    CGSize textSize = [_textLabel.text sizeWithFont:_textLabel.font];
    
    CGFloat x = 2;
    if (self.centerAlignment) {
        x = (self.bounds.size.width-iconSize.width-textSize.width-space)/2;
    }
    x = MAX(x, 0);
	if (self.textFirst) {
		_iconView.frame = CGRectMake(x+textSize.width+space, (self.bounds.size.height-iconSize.height)/2, iconSize.width, iconSize.height);
		_textLabel.frame = CGRectMake(x, (self.bounds.size.height-textSize.height)/2, textSize.width, textSize.height);
	} else {
		_iconView.frame = CGRectMake(x, (self.bounds.size.height-iconSize.height)/2, iconSize.width, iconSize.height);
		_textLabel.frame = CGRectMake(x+iconSize.width+space, (self.bounds.size.height-textSize.height)/2, (self.bounds.size.width-x-iconSize.width-space), textSize.height);
	}
}

@end
